import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { withRouter } from 'react-router-dom';
import { Icon, Tools, SearchBar, TabBar } from 'weaver-mobile';
import { SearchAdvanced, ListViewPage } from 'weaver-mobile-page';
import { renderLoading, renderIsTop, getTemplateBasicItem, getTemplateLinkItem, renderNoData } from '../public';
import { compareParams } from '../../util';
import RouteModal from '../communication/RouteModal';
import BackTop from '../../public/back-to-top';

const getLabel = Tools.getLabel;
@withRouter
@inject('approvalStore')
@observer
export default class Approval extends React.Component {

  static defaultProps = {
    prefixCls: 'cowork-approval-theme',
  }

  constructor(props) {
    super(props);
    this.state = {
      path: props.location.pathname + '/detail',
      coworkId: '',
    }
  }

  componentDidMount() {
    const { approvalStore: { getThemeData, getThemeSearchCondition } } = this.props;
    getThemeData();
    getThemeSearchCondition();
  }

  componentWillUnmount() {
    const { approvalStore: { doThemeMount, closeAllModel, doThemeCancel } } = this.props;
		doThemeMount();
    closeAllModel();
    doThemeCancel();
  }

  getTemplateBasicItemIsTop = (curCls, title, name, isTop) => (
    <div className={`${curCls}-item`}>
      <div className={`${curCls}-item-left`}>{title}:</div>
      <div className={`${curCls}-item-right`}><a>{name}</a>{isTop === '1' && renderIsTop}</div>
    </div>
  );

  getTemplateBottomItem = (curCls, type, name, clickFunc) => (
    <div className={`${curCls}-item`} onClick={clickFunc}>
      <Icon type={type} />
      {name}
    </div>
  )
  
  getTemplate = () => {
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const curCls = "cowork-template-list";
          return (
            <div className={curCls} key={data.id}>
              {this.getTemplateBasicItemIsTop(curCls, getLabel(344,"主题"), data.name,data.isTop)}
              {getTemplateBasicItem(curCls, getLabel(83209,"版块"), data.typeidspan)}
              {getTemplateLinkItem(curCls, getLabel(882,"创建人"), data.createrspan, data.creater)}
              {getTemplateLinkItem(curCls, getLabel(2097,"负责人"), data.principalspan, data.principal)}
              {getTemplateBasicItem(curCls, getLabel(19520,"最后修改时间"), data.lastdiscussantspan, data.lastdiscussant,)}
            </div>
          );
        },
      }],
    };
    return newTemp;
  }

  renderSeparator = (section, index) => {
    const { approvalStore: { showThemeCheck, doThemeApprove, doThemeDelete, themeList } } = this.props;
    const curCls = "cowork-template-bottom";
    const datas = toJS(themeList.data);
    const id = datas[index].id;
    return (
      <div className={`${curCls}-wrap`} key={`${section}_${index}`}>
        {!showThemeCheck && <div className={curCls}>
          {this.getTemplateBottomItem(curCls, 'batch-approval', getLabel(142,"批准"), () => {doThemeApprove({ coworkIds: id })})}
          {this.getTemplateBottomItem(curCls, 'delete', getLabel(91,"删除"), () => {doThemeDelete({ coworkIds: id })})}
        </div>}
      </div>
    );
  }

  render(){
    const { prefixCls, approvalStore, location } = this.props;
    const { themeLoading, themeList, themeSearch, getThemeData, updateThemeAdvance, showThemeCheck, themeAdValue, setStoreState,
    doThemeReset, doThemeDelete, doThemeApprove, doThemeCancel, doThemeSelectAll, doThemeselectNone } = approvalStore;
    let compare = true;
    if (themeSearch) {
      compare = compareParams(toJS(themeSearch.form.formData), toJS(themeSearch.form.defaultValues));
    }
    const adType = compare ? 'filter-o' : 'filter-o-hot';
    const datas = toJS(themeList.data);
    const themeSelectedKeys = toJS(themeList.selectedRowKeys);
    const buttonGroupData = [
      { key: 'reset',
        text: getLabel(2022,"重置"),
        onClick: doThemeReset
      },
      { key: 'submit',
        text: getLabel(826,"确定"),
        onClick: () => {
          getThemeData();
          this.props.history.go(-1);
        },
        type: 'primary',
      }
    ];

    return themeLoading ? renderLoading : (
      <div className={prefixCls}>
        <SearchBar 
          placeholder={getLabel(390654,"请输入主题")}
          value={themeAdValue}
          showExtraButton
          extraButton={[
            { key: 'advanced', show: <Icon type={adType} /> },
          ]}
          onExtraButtonClick={() => this.props.history.push(themeSearch.path)}
          onChange={val => updateThemeAdvance(val)}
          onSubmit={getThemeData}
        />
        <SearchAdvanced
          store={themeSearch}
          buttonGroupData={buttonGroupData}
          onChange={(condition, value) => {if(condition.domkey[0] === 'name') { setStoreState({ themeAdValue: value }); }}}
        />
        {showThemeCheck && (
          <div className="cowork-template-top">
            <span className="cowork-template-top-cancel" onClick={doThemeCancel}>{getLabel(201, '取消')}</span>
            <span>{getLabel(31503,"已选择")}{themeSelectedKeys.length}{getLabel(390655,"个主题")}</span>
            {themeSelectedKeys.length !== datas.length ?
              <span className="cowork-template-top-all" onClick={doThemeSelectAll}>{getLabel(556, '全选')}</span> :
              <span className="cowork-template-top-all" onClick={doThemeselectNone}>{getLabel(387379,"取消全选")}</span>
            }
          </div>
        )}
        <div className={`cowork-template ${showThemeCheck && 'cowork-template-checked'}`}>
          {datas.length === 0 ? renderNoData : (
            <BackTop
              visibilityHeight='200'
              modal
              target='wm-list-view-page-modal-scrollview'
            >
              <ListViewPage.Normal
                store={themeList}
                showCheck={showThemeCheck}
                getTemplate={this.getTemplate}
                renderSeparator={this.renderSeparator}
                onRowClick={(selectedRowKeys) => {
                  this.setState({coworkId: selectedRowKeys.id});
                  // this.props.history.push({pathname:`${location.pathname}/detail`,query:{showBtn:'false',id:selectedRowKeys.id}});
                  this.props.history.push(`${location.pathname}/detail?id=${selectedRowKeys.id}`);
                }}
              />
            </BackTop>
          )}
          {showThemeCheck && (
            <TabBar>
              <TabBar.Item
                title={getLabel(83212,"批量批准")}
                key='approval'
                icon={<Icon type='batch-approval'/>}
                onPress={() => doThemeApprove({ coworkIds: themeSelectedKeys.join(','),dotype:'batch'})}
              />
              <TabBar.Item
                title={getLabel(32136,"批量删除")}
                key='delete'
                icon={<Icon type='delete'/>}
                onPress={() => doThemeDelete({ coworkIds: themeSelectedKeys.join(','),dotype:'batch'})}
              />
            </TabBar>
          )}
        </div>
        <RouteModal/>
      </div>
    );
  }
}